// utils/auth.js

/**
 * 合并权限按钮到现有按钮数组（权限按钮在前）
 * @param {Array} existingButtons 现有按钮数组
 * @param {Array} permissionButtons 权限按钮数组
 * @returns {Array} 合并后的按钮数组（权限按钮在前）
 */
export function mergeButtons(existingButtons = [], permissionButtons = []) {
  // 如果权限按钮数组为空或不存在，直接返回现有按钮
  if (!permissionButtons || permissionButtons.length === 0) {
    return existingButtons;
  }
  
  // 合并两个数组（权限按钮在前）
  return [...permissionButtons, ...existingButtons];
}

/**
 * 获取当前路由对应的权限按钮（带智能类型判断）
 * @param {String} currentPath 当前路由路径
 * @returns {Array} 权限按钮数组
 */
export function getRouteButtons(currentPath) {
  // 从sessionStorage获取菜单数据
  const menus = JSON.parse(sessionStorage.getItem('Menus')) || [];
  
  // 查找当前路由对应的菜单项
  const currentMenu = findMenuByPath(menus, currentPath);
  
  if (!currentMenu || !currentMenu.children) {
    return [];
  }
  
  // 提取类型为F的按钮并智能设置type
  return currentMenu.children
    .filter(item => item.type === 'F')
    .map(button => {
      const title = button.label || button.name || button.title || '';
      let buttonType = 'primary'; // 默认类型
      
      // 根据标题关键字设置类型
      if (title.includes('新增') || title.includes('增加') || title.includes('创建')) {
        buttonType = 'success';
      } else if (title.includes('修改') || title.includes('编辑') || title.includes('更新')) {
        buttonType = 'warning';
      } else if (title.includes('删除') || title.includes('移除')) {
        buttonType = 'danger';
      }
      
      return {
        permission: button.permission,
        title: title,
        icon: button.icon,
        type: buttonType
      };
    });
}

/**
 * 在菜单树中查找匹配路径的菜单项
 */
function findMenuByPath(menus, path) {
  for (const menu of menus) {
    if (menu.path === path) return menu;
    if (menu.children) {
      const found = findMenuByPath(menu.children, path);
      if (found) return found;
    }
  }
  return null;
}